package com.farm.web.controller;

import com.farm.entity.Result;
import com.farm.entity.StatusCode;
import com.farm.web.pojo.CustUser;
import com.farm.web.service.CustUserService;
import com.farm.web.util.CookieUtil;
import com.farm.web.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CustUserService custUserService;


    //登录
    @PostMapping("/login")
    public Result login(@RequestBody CustUser custUser, HttpServletResponse response){
        boolean login = custUserService.login(custUser);
        if (login){
            Map<String,String> info=new HashMap<>();
            info.put("username",custUser.getUsername());
            Map<String,Object> map=new HashMap<>();
            String type = findUser(custUser.getUsername()).getType();
            String username = findUser(custUser.getUsername()).getUsername();
            map.put("haha",type);
            map.put("username",username);
            //生成jwt令牌
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(),map, null);
            info.put(custUser.getUsername(),token);
            redisTemplate.opsForValue().set(custUser.getUsername(),token);
            CustUser custUser1 = findUser(custUser.getUsername());
            //存入cookie
            CookieUtil.addCookie(response,"username",custUser.getUsername(),-1);
            if ("2".equals(custUser1.getStatus())){
                //密码正确
                return new Result(true, StatusCode.OK,"登录成功,您是首次登录请修改密码保证账号的安全",info);
            }else {
                //密码正确
                return new Result(true,StatusCode.OK,"登录成功",info);
            }

        }else {
            //密码错误
            return new Result(true,StatusCode.OK,"登录失败");
        }
    }

    @GetMapping("/outLogin")
    public Result outLogin(HttpServletRequest request,HttpServletResponse response){
        Map<String, String> map = CookieUtil.readCookie(request, "username");
        String username = map.get("username");
        redisTemplate.delete(username+"login");
        redisTemplate.delete(username);
        CookieUtil.addCookie(response,"username","",0);
        return new Result(true,StatusCode.OK,"退出登录");
    }

    //单一查询
    public CustUser findUser(String username){
        CustUser user = custUserService.findUser(username);
        return user;
    }
}
